/**
 * Copyright (C) 2012 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dicodeproject.analysis.pig;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.*;

import java.io.IOException;

/**
 * Splits a string into a bag of 1-element tuples using a delimiter.
 */
public class SplitIntoBag extends EvalFunc<DataBag> {

    private final BagFactory bagFactory = BagFactory.getInstance();
    private final TupleFactory tupleFactory = TupleFactory.getInstance();

    private String delimiter;

    public SplitIntoBag(String delimiter) {
        this.delimiter = delimiter;
    }

    @Override
    public DataBag exec(Tuple input) throws IOException {
        DataBag output = bagFactory.newDefaultBag();
        String s = (String) input.get(0);
        if (s == null) {
            return output;
        }
        for (String el : s.split(delimiter)) {
            output.add(tupleFactory.newTuple(el));
        }
        return output;
    }

}